﻿# Author: Tylor Zhang
# Email: zhangyunqiao@gmail.com

from django import forms
from meet001.meetup.models import Register
from meet001.meetup.models import Group
from django.contrib.auth.models import User
from meet001.meetup.location import location_code, city_district
from meet001.commentboard.models import CommentBoard
import meet001.meetup.location

import uuid
from util import get_thumbnail
try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO


FORM_CHARFIELD_ERROR_MESSAGE = \
    {'required':'该项不能为空',
     'max_length':'长度超过限制',
     'min_length':'长度太短'}

FORM_EMAILFIELD_ERROR_MESSAGE = \
    {'required':'该项不能为空',
     'invalid':'不符合邮件名格式',
     'max_length':'长度超过限制',
     'min_length':'长度太短'}


class UserAlreadyExistsException(Exception):
  def __init__(self):
    Exception.__init__(self, 'User already exists!')

class ProfileUpdateException(Exception):
  def __init__(self):
    Exception.__init__(self, 'Profile Update failed!')

# The form that handle the group creation.
class GroupCreateForm(forms.Form):
  groupname = forms.CharField(
      max_length=50,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  #label = forms.CharField(max_length=100)
  description = forms.CharField(max_length=1024)
#  creator = forms.CharField(max_length=20)
#  email = forms.EmailField(error_messages=FORM_EMAILFIELD_ERROR_MESSAGE)
#  password = forms.CharField(max_length=50, widget=forms.PasswordInput)
  city = forms.CharField(max_length=20)
  district = forms.CharField(max_length=20)
  member_limit = forms.IntegerField()

  
  #added member_limit and found_date
        
  # Save this from to model.
  def save(self, creator):
    if self.is_valid():
      form_data = self.cleaned_data
      new_group = Group()
      # It would be better to use a seperate func to check whether 
      # this group creation is qualified for expeandability, here
      # just check whether name confilicts.
      #if new_group.exist():
      #  raise GroupNameConflictException()
      # Insert a new group to DB.
      new_group.description = form_data['description']
      new_group.creator = User.objects.get(username=creator)
      new_group.name = form_data['groupname']
      new_group.location = location_code[(form_data['city'],
        form_data['district'])] 
      
      #added member_limit and found_date
      new_group.member_limit = form_data['member_limit']
      new_group.comment_board = CommentBoard.create_board()
      new_group.save()
      return new_group.id

# The form that handle the group search.
class GroupSearchForm(forms.Form):
  name = forms.CharField(
      max_length=50,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  city = forms.CharField(max_length=20)
  district = forms.CharField(max_length=20)
  
  def search(self):
    if self.is_valid():
      form_data =self.cleaned_data
      group_name = form_data['name']
      city = form_data['city']
      district = form_data['district']
      groups = Group.objects.filter(name__contains=group_name,
          location=location_code[(city, district)])
      return groups
    return None


# The form that handle the register page.
class RegisterForm(forms.Form):
  email = forms.EmailField(error_messages=FORM_EMAILFIELD_ERROR_MESSAGE)
  name = forms.CharField(
      max_length=20,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  password = forms.CharField(
      max_length=50,
      widget=forms.PasswordInput,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  city = forms.CharField(max_length=20)
  district = forms.CharField(max_length=20)

  # Save this form to model.
  def save(self):
    if self.is_valid():
      cd = self.cleaned_data
      try:
        r = Register.objects.get(pk=cd['email'])
        if r.activated:
          raise UserAlreadyExistsException()
        # Regenerate a uuid
        r.uuid = uuid.uuid4().hex
        r.name = cd['name']
        r.password = cd['password']
        r.location = meet001.meetup.location.location_code[(cd['city'], cd['district'])] 
        r.save()
        return r.uuid, r.email
      except Register.DoesNotExist:
        r = Register()
        r.email = cd['email']
        r.password = cd['password']
        r.uuid = uuid.uuid4().hex
        r.name = cd['name']
        r.location = meet001.meetup.location.location_code[(cd['city'], cd['district'])] 
        r.activated = False
        r.save()
        return r.uuid, r.email

# Simple login form
class LoginForm(forms.Form):
  email = forms.EmailField(error_messages=FORM_EMAILFIELD_ERROR_MESSAGE)
  password = forms.CharField(
      max_length=50,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  remember = forms.BooleanField(required=False)


class ProfileForm(forms.Form):
  sex = forms.CharField(
      max_length=2,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  profession = forms.CharField(
      max_length=50,
      error_messages=FORM_CHARFIELD_ERROR_MESSAGE)
  reason = forms.CharField(required=False)
  photo = forms.ImageField(required=False)
  phone = forms.CharField(required=False)

  def save(self, user):
    if self.is_valid():
      cd = self.cleaned_data
      try:
        profile = user.profile;
        if cd['sex'] != '':
          profile.sex = cd['sex']
        if cd['profession'] != '':
          profile.profession = cd['profession']
        if cd['reason'] != '':
          profile.reason = cd['reason']
        if cd['photo'] is not None:
          profile.photo = 'photos\\' + uuid.uuid4().hex + cd['photo'].name
          image = get_thumbnail(cd['photo'], (120, 120))
          # Generating thumbnail for photos.
          # save it
          image.save(profile.photo.path)
        if cd['phone'] is not None:
          profile.phone = cd['phone']
        profile.save()
      except:
        #raise ProfileUpdateException()
        raise
